package com.hzhr.iot.web.controller;

import com.hzhr.iot.core.util.HzhrTypeUtil;
import com.hzhr.iot.device.sdk.service.Device_AlarmDataService;
import com.hzhr.iot.device.sdk.service.Device_CollectDeviceService;
import com.hzhr.iot.toll.sdk.model.gasUser.GasUserGetModel;
import com.hzhr.iot.toll.sdk.model.gasUser.GasUserModel;
import com.hzhr.iot.toll.sdk.model.gasUser.GasUserPostModel;
import com.hzhr.iot.toll.sdk.model.gasUser.GasUserPutModel;
import com.hzhr.iot.toll.sdk.service.Toll_GasUserService;
import com.hzhr.iot.web.Global;
import com.hzhr.iot.web.constant.TollOptions;
import com.hzhr.iot.web.controller.base.BaseController;
import com.hzhr.iot.web.model.response.BaseResponse;
import com.hzhr.iot.web.util.DateHelper;
import com.hzhr.iot.web.util.StringHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RequestMapping("/gasuser")
@Api(description = "燃气用户管理")
@RestController
public class GasUserController extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    Toll_GasUserService toll_gasUserService;
    @Autowired
    Device_CollectDeviceService device_collectDeviceService;
    @Autowired
    Device_AlarmDataService device_alarmDataService;
    @Autowired
    TollOptions tollOptions;
    @Autowired
    Global global;


    @ApiOperation(value = "查询燃气用户信息", notes = "查询燃气用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uat", value = "用户登录令牌", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "companyid", value = "燃气公司编号", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "type", value = "用户类型 1.个人  2.企业", dataType = "int", required = false, paramType = "query"),
            @ApiImplicitParam(name = "userno", value = "用户编号", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "deptName", value = "所属部门", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "deptCode", value = "所属部门CODE", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "name", value = "用户姓名", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "address", value = "安装地址", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "begintime", value = "开始时间，形如2018-01-01 23:00:00", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "endtime", value = "结束时间，形如2018-01-01 23:00:00", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "pageindex", value = "页数", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "pagesize", value = "每页记录数", dataType = "String", required = false, paramType = "query")
    })
    @RequestMapping(value = "/getgasuserlist", method = RequestMethod.POST)
    BaseResponse getGasuserList(@RequestParam(value = "uat", required = false) String uat
                                , @RequestParam(value = "companyid", required = false, defaultValue = "0") String companyid
            , @RequestParam(value = "type", required = false, defaultValue = "0") Integer type
                                , @RequestParam(value ="userno", required = false,  defaultValue = "") String userno
            , @RequestParam(value ="address", required = false,  defaultValue = "") String address
            , @RequestParam(value ="name", required = false,  defaultValue = "") String name
                                , @RequestParam(value ="deptName", required = false,  defaultValue = "") String deptName
            , @RequestParam(value ="deptCode", required = false,  defaultValue = "") String deptCode
                                , @RequestParam(value ="begintime", required = false) String begintime
                                , @RequestParam(value ="endtime", required = false) String endtime
                                , @RequestParam(value ="pageindex", required = false,  defaultValue = "1") Integer pageindex
                                , @RequestParam(value = "pagesize", required = false, defaultValue = "30") Integer pagesize) throws Exception {
        String token = getToken();
        Map<String, String> header = new HashMap<>();
        header.put("token", token);
        Map<String, Object> query = new HashMap<>();
        query.put("show", "list");
        query.put("page", pageindex);
        query.put("count", pagesize);
        query.put("show_info", true);
        query.put("show_dept", true);
        query.put("show_total", true);

        if (!StringUtils.isEmpty(userno)) {
            query.put("equal_code", userno);
        }
        if (!StringUtils.isEmpty(name)) {
            query.put("like_name", "%" + name + "%");
        }
        if (!StringUtils.isEmpty(address)) {
            query.put("like_address", "%" + address + "%");
        }
        if (!StringUtils.isEmpty(deptCode)) {
            query.put("equal_deptId", "%" + address + "%");
        }
        if (type != null && type != 0) {
            if (type == 260) {
                query.put("equal_typeCode", tollOptions.getCode("GAS_USER_TYPE", "RESIDENTIAL_USER"));
            } else if (type == 261) {
                query.put("equal_typeCode", tollOptions.getCode("GAS_USER_TYPE", "COMMERCIAL_USER"));
            }
        }

        GasUserGetModel gasUserGetModel = toll_gasUserService.get(header, query);
        List<GasUserModel> gasUserModels = gasUserGetModel.getModelList();
        int total = gasUserGetModel.getTotal();

        Map<String, Object> result = new HashMap<>();
        List<Map<String, Object>> dataList = new ArrayList<>();
        for (GasUserModel gasUserModel :
        gasUserModels) {
            Map<String, Object> dataItem = new HashMap<>();
            dataItem.put("id", HzhrTypeUtil.object2string(gasUserModel.getId()));
            dataItem.put("no", HzhrTypeUtil.object2string(gasUserModel.getCode()));
            dataItem.put("name", HzhrTypeUtil.object2string(gasUserModel.getName()));
            String typeCode = HzhrTypeUtil.object2string(gasUserModel.getTypeCode());
            if (typeCode != null) {
                if (typeCode.equals(tollOptions.getCode("GAS_USER_TYPE", "RESIDENTIAL_USER"))) {
                    dataItem.put("type", "260");
                } else if (typeCode.equals(tollOptions.getCode("GAS_USER_TYPE", "COMMERCIAL_USER"))) {
                    dataItem.put("type", "261");
                }
            }
            dataItem.put("gascompanyId", HzhrTypeUtil.object2string(gasUserModel.getCompanyId()));
            dataItem.put("deptId", HzhrTypeUtil.object2string(gasUserModel.getDeptId()));
            dataItem.put("address", HzhrTypeUtil.object2string(gasUserModel.getAddress()));
            dataItem.put("phone", HzhrTypeUtil.object2string(gasUserModel.getPhone()));
            dataItem.put("isvalid", "1");

            Map<String, Object> userDept_deptId = new HashMap<>();
            userDept_deptId.put("name", gasUserModel.getDeptName());
            dataItem.put("userDept_deptId", userDept_deptId);

            dataList.add(dataItem);
        }
        result.put("total", total);
        result.put("dataList", dataList);

        return new BaseResponse("0", "成功", result);
    }

    @ApiOperation(value = "根据用户编号查询燃气用户详情", notes = "根据用户编号查询燃气用户详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uat", value = "用户登录令牌", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "gasuserid", value = "燃气用户编号", dataType = "String", required = true, paramType = "query")
    })
    @RequestMapping(value = "/getgasuser", method = RequestMethod.POST)
    BaseResponse getgasuser( @RequestParam(value = "uat", required = false) String uat
                    , @RequestParam(value = "gasuserid",  defaultValue = "0") String gasuserid ) throws Exception {
        String token = getToken();
        Map<String, String> header = new HashMap<>();
        header.put("token", token);
        Map<String, Object> query = new HashMap<>();
        query.put("show", "one");
        query.put("page", 1);
        query.put("count", 1);
        query.put("equal_id", gasuserid);
        query.put("show_info", true);
        query.put("show_gasConsume", true);
        GasUserModel gasUserModel = toll_gasUserService.get(header, query).getModel();

        Integer gasUserId = gasUserModel.getId();

        Map<String, Object> result = new HashMap<>();
        result.put("id", HzhrTypeUtil.object2string(gasUserId));
        result.put("no", HzhrTypeUtil.object2string(gasUserModel.getCode()));
        result.put("name", HzhrTypeUtil.object2string(gasUserModel.getName()));
        String typeCode = HzhrTypeUtil.object2string(gasUserModel.getTypeCode());
        if (typeCode != null) {
            if (typeCode.equals(tollOptions.getCode("GAS_USER_TYPE", "RESIDENTIAL_USER"))) {
                result.put("type", "260");
            } else if (typeCode.equals(tollOptions.getCode("GAS_USER_TYPE", "COMMERCIAL_USER"))) {
                result.put("type", "261");
            }
        }
        result.put("deptId", HzhrTypeUtil.object2string(gasUserModel.getDeptId()));
        result.put("address", HzhrTypeUtil.object2string(gasUserModel.getAddress()));
        result.put("phone", HzhrTypeUtil.object2string(gasUserModel.getPhone()));
        result.put("isvalid", "1");

        header = new HashMap<>();
        String globalToken = global.getFirstToken();
        header.put("token", globalToken);
        query = new HashMap<>();
        query.put("_equal_gasUserId", gasUserId);
        query.put("_show_total", true);
        Integer total = device_collectDeviceService.get(header, query).getTotal();
        result.put("collectdevicenum", total);

        header = new HashMap<>();
        header.put("token", globalToken);
        query = new HashMap<>();
        query.put("_equal_gasUserId", gasUserId);
        query.put("_show_total", true);
        total = device_alarmDataService.get(header, query).getTotal();
        result.put("alarmdataCount", total);

        result.put("gasconsumeCount", HzhrTypeUtil.object2string(gasUserModel.getGasConsume()));

        return new BaseResponse("0", "成功", result);
    }

    @ApiOperation(value = "列表页顶部统计数据", notes = "列表页顶部统计数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uat", value = "用户登录令牌", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "gascompanyid", value = "然气公司ID", dataType = "String", required = false, paramType = "query")
    })
    @RequestMapping(value = "/listtopcount", method = RequestMethod.POST)
    BaseResponse listtopcount(@RequestParam(value = "uat", required = true) String uat,
                              @RequestParam(value = "gascompanyid", required = false,defaultValue="0") String gascompanyid) throws Exception {
        String token = getToken();
        Map<String, String> header = new HashMap<>();
        header.put("token", token);
        Map<String, Object> query = new HashMap<>();
        query.put("show_total", true);

        query.put("greaterthanorequal_createTime", DateHelper.getTimesWeekmorning().getTime());
        int weekAddCount = toll_gasUserService.get(header, query).getTotal();
        query.put("greaterthanorequal_createTime", DateHelper.getDayEndTime(new Date()).getTime());
        int yesterdayAddCount = toll_gasUserService.get(header, query).getTotal();
        query.put("greaterthanorequal_createTime", DateHelper.getMonthBeginTime(new Date()).getTime());
        int monthAddCount = toll_gasUserService.get(header, query).getTotal();
        query.put("greaterthanorequal_createTime", DateHelper.getCurrYearFirst().getTime());
        int yearAddCount = toll_gasUserService.get(header, query).getTotal();
        query.put("greaterthanorequal_createTime", null);
        int userCount = toll_gasUserService.get(header, query).getTotal();


        HashMap<String,Object> map=new HashMap<>();
        map.put("WeekAddCount",weekAddCount);//周新增用户
        map.put("YesterdayAddCount",yesterdayAddCount);//昨日新增用户
        map.put("MonthAddCount",monthAddCount);//本月新增用户
        map.put("YearCount",yearAddCount);//今年新增用户
        map.put("UserCount",userCount);//用户总数

        return new BaseResponse("0", "成功",map);

    }

    @ApiOperation(value = "新增燃气用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "用户名,最多允许输入10个字符", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "code", value = "用户号, 最多允许输入30个字符", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "phone", value = "手机号码,11位数字", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "regioncode", value = "地区编码,10个字符", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "address", value = "详细地址,最多允许输入50个字符", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "type", value = "用户类型,1 个人 2 企业 默认 1", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "uat", value = "用户登录令牌", dataType = "String", required = true, paramType = "query"),
    })
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    BaseResponse add(@RequestParam(value = "name", required = true) String name
            , @RequestParam(value = "code", required = true) String code
            , @RequestParam(value = "phone", required = true) String phone
            , @RequestParam(value = "regioncode", required = false) String regioncode
            , @RequestParam(value = "address", required = true) String address
            , @RequestParam(value = "type", required = false, defaultValue = "1") int type
            , @RequestParam(value = "uat", required = true) String uat ) throws Exception {
        if (StringHelper.isTrimEmpty(name)){
            return new BaseResponse("120", "用户姓名不能为空");
        }
        if (StringHelper.isTrimEmpty(address)){
            return new BaseResponse("124", "地址不能为空");
        }

        String token = getToken();
        Map<String, String> header = new HashMap<>();
        header.put("token", token);
        Map<String, Object> query = new HashMap<>();

        GasUserPostModel gasUser = new GasUserPostModel();
        gasUser.setCode(code);
        gasUser.setName(name);
        gasUser.setAddress(address);
        gasUser.setPhone(HzhrTypeUtil.string2long(phone));
        if (type == 260) {
            gasUser.setTypeCode(tollOptions.getCode("GAS_USER_TYPE", "RESIDENTIAL_USER"));
        } else if (type == 261) {
            gasUser.setTypeCode(tollOptions.getCode("GAS_USER_TYPE", "COMMERCIAL_USER"));
        }
        toll_gasUserService.post(header, query, gasUser);

        return new BaseResponse("0", "燃气用户创建成功");
    }

    @ApiOperation(value = "编辑燃气用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "用户名,最多允许输入10个字符", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "phone", value = "手机号码,11位数字", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "no", value = "用户编号", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "address", value = "详细地址,最多允许输入50个字符", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "type", value = "用户类型,1 个人 2 企业 默认 1", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "id", value = "用户编号", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "uat", value = "用户登录令牌", dataType = "String", required = true, paramType = "query"),
    })
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    BaseResponse edit(@RequestParam(value = "name", required = true) String name
            , @RequestParam(value = "phone", required = true) String phone
            , @RequestParam(value = "no", required = true) String no
            , @RequestParam(value = "address", required = true) String address
            , @RequestParam(value = "type", required = false, defaultValue = "1") int type
            , @RequestParam(value = "id", required = true) String id
            , @RequestParam(value = "uat", required = true) String uat ) throws Exception {
        if (StringHelper.isTrimEmpty(name)){
            return new BaseResponse("120", "用户姓名不能为空");
        }
        if (StringHelper.isTrimEmpty(no)){
            return new BaseResponse("121", "用户号不能为空");
        }
        if (StringHelper.isTrimEmpty(address)){
            return new BaseResponse("124", "地址不能为空");
        }

        String token = getToken();
        Map<String, String> header = new HashMap<>();
        header.put("token", token);
        Map<String, Object> query = new HashMap<>();

        GasUserPutModel gasUser = new GasUserPutModel();
        gasUser.setCode(no);
        gasUser.setName(name);
        gasUser.setAddress(address);
        gasUser.setPhone(HzhrTypeUtil.string2long(phone));
        if (type == 260) {
            gasUser.setTypeCode(tollOptions.getCode("GAS_USER_TYPE", "RESIDENTIAL_USER"));
        } else if (type == 261) {
            gasUser.setTypeCode(tollOptions.getCode("GAS_USER_TYPE", "COMMERCIAL_USER"));
        }
        toll_gasUserService.putById(header, Integer.parseInt(id), query, gasUser);

        return new BaseResponse("0", "燃气用户编辑成功");
    }

    @ApiOperation(value = "删除燃气用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户编号", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "uat", value = "用户登录令牌", dataType = "String", required = true, paramType = "query"),
    })
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    BaseResponse delete(@RequestParam(value = "id", required = true) String id
            , @RequestParam(value = "uat", required = true) String uat ) throws Exception {
        String token = getToken();
        Map<String, String> header = new HashMap<>();
        header.put("token", token);
        Map<String, Object> query = new HashMap<>();

        toll_gasUserService.deleteById(header, Integer.parseInt(id), query);
        return new BaseResponse("0", "燃气用户删除成功");
    }


}
